package org.uturn.timeshift.web.menus.utils;

import org.primefaces.model.menu.DefaultMenuItem;
import org.primefaces.model.menu.DefaultMenuModel;
import org.primefaces.model.menu.DefaultSubMenu;
import org.primefaces.model.menu.MenuElement;
import org.uturn.timeshift.utils.utils.XMLConverter;

import javax.faces.context.FacesContext;

import java.io.File;
import java.io.IOException;
import java.util.*;

/**
 * Created by przemyslaw.sudak on 2/26/2015.
 */
public class MenuUtils {

    public static String INDEX = "index";
    public static String LOGIN = "login";

    public String getXHTMLFilePageName(){
        String uri = FacesContext.getCurrentInstance().getViewRoot().getViewId();
        String pageName = "";

        if(uri.contains(".xhtml")){
            pageName = uri.substring(uri.lastIndexOf("/")+1,uri.lastIndexOf("."));
        }

        return pageName;
    }

    public DefaultMenuModel getMenu(String menuTemplateName){

        XMLConverter xmlConverter = new XMLConverter();

        MenuModel model = new MenuModel();

        DefaultMenuModel menuModel = new DefaultMenuModel();

        try {
            model = (MenuModel) xmlConverter.jaxbXMLToObject("xml/menu/"+menuTemplateName+".xml");
        } catch (IOException e) {
            e.printStackTrace();
        }

        if(model==null){
            return null;
        }

        List<ItemMenuModel> items = new ArrayList<ItemMenuModel>(model.items);
        Collections.sort(items);

        DefaultSubMenu subMenu = null;

        for(String subMenuTitle : getSubMenusTitles(items)){

            subMenu = new DefaultSubMenu(subMenuTitle);

            for(Iterator<ItemMenuModel> i = items.iterator();i.hasNext();){
                ItemMenuModel m = i.next();

                DefaultMenuItem item = new DefaultMenuItem(m.getName());
                item.setIcon(m.getIcon());
                item.setUpdate(m.getUpdate());
                item.setHref(m.getHref());

                if(m.getSubmenuTitle()!= null && m.getSubmenuTitle().equals(subMenuTitle)){
                    subMenu.addElement(item);
                }
            }

            menuModel.addElement(subMenu);
        }

        return menuModel;
    }

    private Set<String> getSubMenusTitles(List<ItemMenuModel> items){
        Set<String> subMenuSet = new TreeSet<String>();

        for(Iterator<ItemMenuModel> i = items.iterator(); i.hasNext();){
            String title = i.next().getSubmenuTitle();
            if(title == null)
                title = "";
            subMenuSet.add(title);
        }

        return subMenuSet;
    }

}
